package com.lyf.controll;

import cn.hutool.json.JSONObject;
import com.lyf.pojo.User;
import com.lyf.result.Code;
import com.lyf.result.Result;
import com.lyf.service.UserService;
import com.lyf.service.impl.UserServiceImpl;
import com.lyf.utils.CrossRegion;
import com.lyf.utils.ResponseResult;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class loginControll extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决跨域
//        CrossRegion.setCross(resp);
        UserService userService = new UserServiceImpl();

        String loginname = req.getParameter("loginname");
        String password = req.getParameter("password");
        String role = req.getParameter("role");

        if(!loginname.equals("") && !loginname.isEmpty() &&
           !password.equals("") && !password.isEmpty()
        ){
            User user = userService.login(loginname, password);
            if(user != null ){
                if(user.getStatus() == 0 ||user.getStatus() == 2 || user.getIsdelete() == 1){
                    Result result = new Result(Code.Fail,null,"你的账号被禁用或者已注销，请联系管理员喔！");
                    ResponseResult.sendResult(resp,result);
                } else{
                    Map<String,Object> map = new HashMap<>();
                    Result result = new Result(Code.OK,user,"登陆成功！");
                    JSONObject jo = new JSONObject();

                    map.put("result",result);
                    jo.putAll(map);
                    //存储到redis
                    Jedis jedis = new Jedis("127.0.0.1",6379);
                    jedis.auth("123456");
                    //过期时间为12小时
                    jedis.setex("id",60*60*12,Integer.toString(user.getId()));
                    jedis.setex("loginname",60*60*12,user.getLoginname());
                    //响应到浏览器
                    resp.getWriter().println(jo.toString());
                }
            }else{
                Map<String,Object> map = new HashMap<>();
                Result result = new Result(Code.Fail,null,"用户名或密码错误！");
                JSONObject jo = new JSONObject();

                map.put("result",result);
                jo.putAll(map);

                //响应到浏览器
                resp.getWriter().println(jo.toString());
            }
        }




    }
}
